import axios from 'axios'
import qs from 'qs'
import store from '@/store/index.js'
import router from '@/router/'
import {Modal} from 'ant-design-vue'
import {baseUrl} from '@/config'
import storage from '@/utils/storage'
import md5 from 'js-md5'
import moment from 'moment'
import {appConfig} from '../config/app'

const statusMap = {
  401: '无权限调用此服务！',
  404: '找不到对应的地址！',
  500: '服务器处理出错！',
  504: '服务器返回超时！'
}
const errorCodeMap = {
  '3034': '身份认证过期或错误，请重新登录！',
  '-100': '认证过期',
  '-99': '您的账号在其他地方已登录，请重新登录！',
  '-98': '没有该功能权限！',
  '-101': '长时间未操作，请重新登录！'
}

axios.interceptors.request.use(
  config => {
    store.commit('showloadding', true)
    storage.session.get('authToken') && (config.headers['Authorization'] = 'Bearer ' + storage.session.get('authToken'))
    storage.session.get('role') && (config.headers['role'] = storage.session.get('role'))

    if (config.headers['Authorization']) {
      let authorization = config.headers['Authorization']
      let tDate = Math.round(moment.now() * 1000)
      config.headers['t'] = tDate
      config.headers['skey'] = md5(tDate + authorization)
    }

    if (config.method === 'get') {
      ;(config.data &&
        (config.params = {
          t: new Date().getTime(),
          ...config.data
        })) ||
      (config.params = {
        t: new Date().getTime(),
        ...config.params
      })
    } else if (config.method === 'post') {
      if (
        config.headers['Content-Type'] &&
        config.headers['Content-Type'] === 'application/x-www-form-urlencoded'
      ) {
        config.data = qs.stringify({...config.data})
      }
    } else if (config.method.toUpperCase() === 'FILEUPLOAD') {
      config.method = 'post'
      const data = config.data
      let fileData = new FormData()
      if (data.fileList) {
        const fileList = data.fileList
        for (const key in fileList) {
          if (fileList.hasOwnProperty(key)) {
            if (Array.isArray(fileList[key])) {
              for (let i = 0; i < fileList[key].length; i++) {
                if (fileList[key][i].originFileObj) {
                  fileData.append(key, fileList[key][i].originFileObj)
                }
              }
            } else if (fileList[key].originFileObj) {
              fileData.append(key, fileList[key].originFileObj)
            }
          }
        }
      }
      for (const item in data) {
        if (item !== 'fileList') {
          // if (item && data[item + '']) {
          //   if (typeof data[item + ''] === "object") {
          //     fileData.append(item + '', JSON.stringify(data[item + '']));
          //   } else {
          //     fileData.append(item + '', data[item + ''] + '');
          //   }
          // }
          if (
            item !== null &&
            data[item] !== undefined &&
            data[item] !== null
          ) {
            if (typeof data[item] === 'object') {
              fileData.append(item + '', JSON.stringify(data[item + '']))
            } else {
              // 除了文件之外的 其他参数 用这个循环加到filedata中
              fileData.append(item, data[item])
            }
          }
        }
      }
      config.data = fileData
    }
    return config
  },
  error => {
    return Promise.reject(error)
  }
)

axios.interceptors.response.use(
  response => {
    store.commit('showloadding', false)
    if (response.status == 200) {
      let data = response.data
      // 有错误编码，编码小于0，或者编码大于1000000 并且小于 9900000时表示是有错误的信息，需要提示  -1000: api在线测试错误码-不展示错误弹窗
      if (data.code && (data.code !== 0 && data.code !== 1 && data.code !== 201 && data.code !== -1000)) {
        // 单点登录失败返回code是-1时
        if (response.config.url.indexOf('api/sso/login') != -1) {
          return data
        }
        let content = errorCodeMap[data.code] || errorCodeMap[data.code + ''] || data.message
        if (!store.state.dialogFlag) {
          store.commit('setDialogFlag', true)
          Modal.error({
            content: content,
            onOk () {
              store.commit('setDialogFlag', false)
              if (errorCodeMap[data.code] || errorCodeMap[data.code + '']) {
                storage.session.remove('isLogin')
                storage.session.remove('authToken')
                storage.session.remove('userInfo')
                storage.session.remove('topPermTree')
                storage.session.remove('role')
                storage.session.remove('roles')
                storage.session.remove('gldToken')
				storage.session.remove('wallet')
                if (appConfig.loginUrl) {
                  window.location.href = appConfig.loginUrl
                }
              }
            }
          })
          return {}
        }
      }
      return response.request.responseType === 'blob' ? response : data
    } else {
      if (!store.state.dialogFlag) {
        store.commit('setDialogFlag', true)
        Modal.error({
          content:
            'status:' +
            response.status +
            ',' +
            (statusMap[response.status] || '网络错误，请重试') +
            response.data.message,
          mask: false,
          onOk () {
            // delete appConfig.errorModal;
            store.commit('setDialogFlag', false)
          }
        })
      }
    }
  },
  error => {
    store.commit('showloadding', false)
    if (error.response) {
      if (!store.state.dialogFlag) {
        store.commit('setDialogFlag', true)
        Modal.error({
          content:
            'error:' +
            error.response.status +
            ',' +
            (statusMap[error.response.status] || '网络错误，请重试') +
            error.response.data.message,
          mask: false,
          onOk () {
            // delete appConfig.errorModal;
            store.commit('setDialogFlag', false)
          }
        })
      }
    }
    return Promise.reject(error.response) // 返回接口返回的错误信息
  }
)

function request (url, options = {}) {
  return axios({url: baseUrl + url, ...options})
}

export function setHeader (name, value) {
  axios.defaults.headers.common[name] = value
}

export function deleteHeader (name) {
  delete axios.defaults.headers.common[name]
}

export const axios_ = axios
export const qs_ = qs

export default request
